package com.github.ghsea.kafka.config;

import cn.hutool.core.net.NetUtil;
import com.github.ghsea.kafka.JsonUtils;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.RetryingBatchErrorHandler;
import org.springframework.util.backoff.FixedBackOff;

/**
 * @author guhai
 */
@Configuration
@Getter
@Setter
@Slf4j
@EnableKafka
@SuppressWarnings("ALL")
public class KafkaConfiguration {

    /**
     * 消费配置
     *
     * @return
     */

    private Map<String, Object> consumerConfigs(KafkaProperties kafkaProperties) {
        ConsumerProperties consumerConfig=kafkaProperties.getConsumer();
        Map<String, Object> props = new HashMap<>(12);
        // 注意这里的address ，保持和容器一致
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers());
        props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, consumerConfig.isEnableAutoCommit());
        if (consumerConfig.isEnableAutoCommit()) {
            props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, consumerConfig.getAutoCommitIntervalMs());
        }
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, consumerConfig.getKeyDeserializer());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, consumerConfig.getValueDeserializer());
        props.put(ConsumerConfig.GROUP_ID_CONFIG, consumerConfig.getGroupId());
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, consumerConfig.getAutoOffsetReset());
        props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 100);
        if (consumerConfig.getIsolationLevel() != null) {
            props.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, consumerConfig.getIsolationLevel());
        }

        log.info("Kafka consumer configurations={}", JsonUtils.toJSONString(props));

        return props;
    }

    /**
     * 获取工厂
     */
    @Bean
    @ConditionalOnProperty(prefix = "kafka.consumer",name = "keySerializer")
    public ConsumerFactory<String, String> consumerFactory(KafkaProperties kafkaProperties) {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs(kafkaProperties));
    }

    /**
     * 构建推送消息工厂
     *
     * @return
     */
    public ProducerFactory<String, String> producerFactory(ProducerProperties producerProperties) {
        Map<String, Object> props = new HashMap<>(8);
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, producerProperties.getBatchSize());
        props.put(ProducerConfig.RETRIES_CONFIG, producerProperties.getProduceReties());
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, producerProperties.getBatchSize());
        props.put(ProducerConfig.LINGER_MS_CONFIG, producerProperties.getLingerMs());
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, producerProperties.getBufferMemory());
        props.put(ProducerConfig.ACKS_CONFIG, producerProperties.getAcks());
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, producerProperties.getKeySerializer());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, producerProperties.getValueSerializer());
        if (producerProperties.getTransactionPrefix() != null) {
            props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, getTransactionId(producerProperties.getTransactionPrefix()));
        }
        props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, producerProperties.getCompressionType());

        log.info("Kafka producer configurations={}", JsonUtils.toJSONString(props));
        return new DefaultKafkaProducerFactory<>(props);
    }

    /**
     * 定义 kafkaTemplate bean ,后面通过依赖注入的方式获取
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "kafka.producer",name = "keySerializer")
    public KafkaTemplate<String, String> kafkaTemplate(KafkaProperties kafkaProperties) {
        return new KafkaTemplate<>(producerFactory(kafkaProperties.getProducer()));
    }

    /**
     * 构建批量消费者工厂 （副容器），这个地方需要注意 ，不同的kafka 容器 需要构建 不同的factory ，以此来加载相应的消费者listener
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "kafka.consumer",name = "keySerializer")
    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> batchConsumeFactory(KafkaProperties kafkaProperties,KafkaTemplate<String,String> kafkaTemplate) {
        ConcurrentKafkaListenerContainerFactory<String, String> factory =
                new ConcurrentKafkaListenerContainerFactory<>();
        ConsumerProperties consumerProperties = kafkaProperties.getConsumer();
        factory.setConsumerFactory(consumerFactory(kafkaProperties));
        // 注意这里监听的消费者数量，保持跟分区数一致
        factory.setConcurrency(consumerProperties.getPartitionNum());
        factory.setBatchListener(true);
        factory.setAutoStartup(true);
        factory.getContainerProperties().setPollTimeout(3000);
        factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);

        RetryingBatchErrorHandler errorHandler = new RetryingBatchErrorHandler(new FixedBackOff(1000, 3), new DeadLetterPublishingRecoverer(kafkaTemplate));
        factory.setBatchErrorHandler(errorHandler);
        return factory;
    }


    private String getTransactionId(String transactionPrefix) {
        String localhostStr = NetUtil.getLocalhostStr();
        if (localhostStr == null) {
            localhostStr = String.valueOf(System.currentTimeMillis());
        }

        return transactionPrefix + localhostStr + "-";
    }

}
